package com.google.code.yargon.ui.lighting;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Arrays;

@SuppressWarnings("serial")
public class Ray extends Line2D.Float {
	
	// Coordinates of the block (in block units) where this ray points to
	private int bx;
	private int by;
		
	// Array of all block intersections, for visibility testing 
	private Intersection[] is;
	
	public Ray(Point2D p0, Point2D p1, int bx, int by) {
		super(p0, p1);
		this.bx = bx;
		this.by = by;	
	}

	/**
	 * Get this ray's destination blocks x-coordinate in block units
	 * 
	 * @return
	 */
	public int getBlockX() {
		return bx;
	}

	/**
	 * Get this ray's destination blocks x-coordinate in block units
	 * 
	 * @return
	 */
	public int getBlockY() {
		return by;
	}	
	
	/**
	 * Set the blocks that this ray intersects as Point2D objects, in block units
	 * 
	 * @param blocks
	 */
	public void setIntersections(Intersection[] is) {
		this.is = is;
		sortIntersections();
	}
	
	/**
	 * Get the blocks that this ray intersects as Point2D objects, in block units
	 * 
	 * @return
	 */
	public Intersection[] getIntersections() {
		return is;
	}
	
	/**
	 * Translate the intersections by swapping their x- and y-coordinates
	 * 
	 */
	public void swapIntersectionsXY() {
		Intersection[] tmp = new Intersection[is.length];
		for(int i = 0; i < is.length; i++) {
			tmp[i] = new Intersection(is[i].getY(), is[i].getX());
		}
		is = tmp;
		sortIntersections();
	}
	
	/**
	 * Translate the intersected blocks by inverting their x-coordinates
	 * 
	 */
	public void invertIntersectionsX() {
		Intersection[] tmp = new Intersection[is.length];
		for(int i = 0; i < is.length; i++) {
			tmp[i] = new Intersection(-is[i].getX(), is[i].getY());
		}
		is = tmp;
		sortIntersections();
	}
	
	/**
	 * Translate the intersected blocks by inverting their y-coordinates
	 * 
	 */
	public void invertIntersectionsY() {
		Intersection[] tmp = new Intersection[is.length];
		for(int i = 0; i < is.length; i++) {
			tmp[i] = new Intersection(is[i].getX(), -is[i].getY());
		}
		is = tmp;
		sortIntersections();
	}
		
	/**
	 * Sort the intersected blocks in order of distance from player, nearest first
	 * 
	 */
	private void sortIntersections() {
		Arrays.sort(is);
	}
}
